<template>
  <div class="container mx-auto p-4">
    <!-- 标题和操作按钮区域 -->
    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
      <h1 class="text-2xl font-bold text-gray-800">{{ t('便携式电池护照管理') }}</h1>
      <div class="flex flex-wrap gap-2">
        <el-button type="primary" @click="handleManualCreate">
          <i class="el-icon-plus mr-1"></i>{{ t('手动录入') }}
        </el-button>
        <el-button type="primary" @click="handleApiImport">
          <i class="el-icon-connection mr-1"></i>{{ t('API导入') }}
        </el-button>
        <el-button type="primary" @click="handleExcelImport">
          <i class="el-icon-upload2 mr-1"></i>{{ t('Excel导入') }}
        </el-button>
        <el-button type="success" @click="handleExport">
          <i class="el-icon-download mr-1"></i>{{ t('Excel导出') }}
        </el-button>
      </div>
    </div>

    <!-- 搜索条件区域 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 p-4 bg-gray-50 rounded-lg mb-6">
      <el-input
          v-model="queryParams.batteryPassportId"
          :placeholder="t('便携式电池护照标识')"
          clearable
          @keyup.enter="handleSearch"
      ></el-input>

      <el-select
          v-model="queryParams.batteryCategory"
          :placeholder="t('便携式电池类别')"
          clearable
          filterable
      >
        <el-option v-for="(item, index) in BatteryCategory" :key="index" :label="item.label"
                   :value="item.value"></el-option>
      </el-select>

      <el-select
          v-model="queryParams.documentStatus"
          :placeholder="t('便携式电池状态')"
          clearable
          filterable
      >
        <el-option v-for="(item, index) in document_status" :key="index" :label="item.label"
                   :value="item.value"></el-option>
      </el-select>

      <div class="flex gap-2">
        <el-button :loading="loading" type="primary" @click="handleSearch">
          {{ t('搜索') }}
        </el-button>
        <el-button :disabled="loading" @click="resetSearch">
          {{ t('重置') }}
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="bg-white rounded-lg shadow">
      <el-table
          v-loading="loading"
          :data="pageData.records"
          :empty-text="t('暂无便携式电池数据')"
          class="w-full"
          stripe
          @row-click="handleRowClick"
      >
        <el-table-column v-for="column in tableColumns" :key="column.prop"
                         :align="column.align"
                         :fixed="column.fixed"
                         :label="column.label"
                         :min-width="column.minWidth"
                         :prop="column.prop"
                         :show-overflow-tooltip="column.showOverflowTooltip"
                         :width="column.width">
        </el-table-column>
        <el-table-column :label="t('操作')" width="250">
          <template #default="scope">
            <el-button @click="handleView(scope.row.id)">{{ t('查看') }}</el-button>
            <el-button @click="handleEdit(scope.row.id)">{{ t('编辑') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="flex justify-between items-center mt-4">
      <el-pagination
          v-model:current-page="pageData.current"
          v-model:page-size="pageData.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pageData.total"
          :disabled="loading"
          layout="prev, pager, next, sizes"
          @size-change="fetchData"
          @current-change="fetchData"
      ></el-pagination>
    </div>

    <ImportDialog
        v-model="importDialogVisible"
        title="导入数据"
        :import-api=portable_batter_import
        :template-api=portable_batter_import_template
        :headers="{ 'X-Custom-Header': 'value' }"
        :extra-data="{ type: 'forum' }"
        tip-text="支持 .xlsx, .xls, .csv 格式文件，文件大小不超过 10MB"
    />
  </div>
</template>
<script setup>
import {onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import PortableBatteryApi from '@/api/portableBatteryApi.js'
import {
  BatteryCategory,
  document_status,
  portable_batter_import, portable_batter_import_export,
  portable_batter_import_template
} from "@/api/_const.js";
import {portableBatteryCreate, portableBatteryDetail, portableBatteryEdit} from "@/router/index.js";
import {useI18n} from "vue-i18n";
import ImportDialog from "@/components/ImportDialog.vue";
import {downloadFileV2} from "@/utils/download.js";

const {t} = useI18n()
const router = useRouter()
const loading = ref(false)
const importDialogVisible = ref(false)

// 表格列配置 - 使用"便携式电池"作为字段显示
const tableColumns = ref([
  {prop: 'batteryPassportId', label: t('电池护照标识'), minWidth: '220', type: 'link', showOverflowTooltip: true},
  {prop: 'batteryId', label: t('电池标识'), minWidth: '180', showOverflowTooltip: true},
  {prop: 'manufacturerId', label: t('制造商'), minWidth: '200', showOverflowTooltip: true},
  {prop: 'manufacturingLocation', label: t('制造地点'), minWidth: '250', showOverflowTooltip: true},
  {prop: 'manufacturingDate', label: t('制造日期'), minWidth: '140', type: 'date'},
])

let pageData = reactive({
  current: 1,
  size: 10,
  total: 0,
  records: []
})

const queryParams = reactive({
  batteryCategory: '',
  batteryPassportId: '',
  documentStatus: '',
  manufacturingStart: '',
  manufacturingEnd: '',
  minBatteryMass: null,
  maxBatteryMass: null
})

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      current: pageData.current,
      size: pageData.size,
      ...queryParams
    }
    const res = await PortableBatteryApi.getBatteryPassports(params)
    if (res.code === 200) {
      pageData = res.data
    } else {
      console.error('获取数据失败:', res.message)
    }
  } catch (error) {
    
    console.error('获取便携式电池列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pageData.current = 1
  fetchData()
}

const resetSearch = () => {
  Object.keys(queryParams).forEach(key => {
    if (key.includes('min') || key.includes('max')) {
      queryParams[key] = null
    } else {
      queryParams[key] = ''
    }
  })
  handleSearch()
}

const handleRowClick = (row) => {
  handleView(row.id)
}

const handleView = (id) => {
  router.push({
    name: portableBatteryDetail,
    params: {id}
  })
}

const handleEdit = (id) => {
  router.push({name: portableBatteryEdit, params: {id}})
}

const handleManualCreate = () => {
  router.push({name: portableBatteryCreate})
}

const handleExcelImport = () => {
  // Excel导入逻辑
  importDialogVisible.value = true
  console.log('Excel导入便携式电池数据')
}

const handleApiImport = () => {
  // API导入逻辑
  console.log('API导入便携式电池数据')
}

const handleExport = () => {
  // 导出逻辑
  console.log('导出便携式电池数据')
  downloadFileV2(queryParams, portable_batter_import_export, "便携式电池.xlsx" )
}

onMounted(() => {
  fetchData()
})
</script>
<style scoped>
</style>